/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.server;

import org.jklawrencefam.Util.LogFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: John Lawrence
 * Date: 7/13/11
 * Time: 8:58 PM
 */
public abstract class Processor extends Thread {
    private Logger logger = LogFactory.getLogger(Processor.class);
    protected Socket socket;
    protected Scanner incoming;
    protected PrintStream out;

    public final void setSocket(Socket socket) {
        try {
            this.socket = socket;
            out = new PrintStream(socket.getOutputStream());
            incoming = new Scanner(socket.getInputStream());
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error setting up communications with client", e);
            System.exit(45);
        }
    }

    public abstract void run();

    protected void closeConnections() {
        logger.fine("Closing the connections");
        if (incoming != null) {
            incoming.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Error closing socket.", e);
            }
        }
    }
}
